'use client';

import { useState, useCallback, useRef, useEffect } from 'react';
// 使用打包后的 WRPlayer
import WRPlayer from '../../../dist/wrplayer.esm.js';
import PtzControls from './components/PtzControls.jsx';
import PtzPresets from './components/PtzPresets.jsx';
import PtzAdvanced from './components/PtzAdvanced.jsx';
import ptzApi from './utils/ptzApi.js';
import './globals.css';

export default function PlayerDemo() {
  const [videoUrl, setVideoUrl] = useState('http://222.222.25.198:6080/index/api/webrtc?app=rtp&stream=34020000001320000009_34020000001320000009&type=play&originTypeStr=rtp_push');
  const [logs, setLogs] = useState([]);
  const [isPlaying, setIsPlaying] = useState(false);
  const [showPlayer, setShowPlayer] = useState(false); // 控制是否显示播放器
  const [currentUrl, setCurrentUrl] = useState(''); // 当前正在播放的URL
  const [retryCount, setRetryCount] = useState(0); // 重试次数
  const [needsUserInteraction, setNeedsUserInteraction] = useState(false); // 是否需要用户交互
  const [isMuted, setIsMuted] = useState(true); // 静音状态
  
  // PTZ 相关状态
  const [showPtzControls, setShowPtzControls] = useState(false);
  const [ptzApiUrl, setPtzApiUrl] = useState('http://222.222.25.198:18082'); // SIP服务地址
  const [ptzToken, setPtzToken] = useState('eyJhbGciOiJSUzI1NiIsImtpZCI6IjNlNzk2NDZjNGRiYzQwODM4M2E5ZWVkMDlmMmI4NWFlIn0.eyJqdGkiOiJSNGhUSDRyaVlNRmdMR2tJQldWbUZnIiwiaWF0IjoxNzU3Mzk5OTE2LCJleHAiOjIyNjgyNTk1OTYyMzUzMiwibmJmIjoxNzU3Mzk5OTE2LCJzdWIiOiJsb2dpbiIsImF1ZCI6IkF1ZGllbmNlIiwidXNlck5hbWUiOiJhZG1pbiIsImFwaUtleUlkIjoxfQ.eo6LUq2LGXV-KJ93b6ebspY_789wGQm482w4BNffNz5hLVITNjA6m5vXPprrf_mQUnuZvsoQCid_bjumClM1KToKQ23UBsiw19oOS75c4dln9eJwl83A0wmK3Yp5kPj-6eKsRQi4Jb_2kee8s0NqyKt4bUmNocp-E89rSrHfr-_Vo5ckfFAOA2fdITo70Qhco3dir1LEmQKMCjYqSGbfnqwg7bf5lLBmApFBhyj58MJV6HLtr6X383UzKWu-0gejzb4tEcQqiVqlWQUGw_PSq-fAJgJUe3_TttChVWdXcbyzgzFIkrlbijJtUeMWxcva2zuXFQCiOe0h2vgJMG7XbA'); // API认证token
  const [deviceId, setDeviceId] = useState('34020000001320000009'); // 设备ID
  const [channelId, setChannelId] = useState('34020000001320000009'); // 通道ID
  const [useProxy, setUseProxy] = useState(true); // 是否使用代理
  
  const playerRef = useRef(null);
  const videoRef = useRef(null);
  const wrPlayerInstance = useRef(null);

  const addLog = useCallback((message, data = '') => {
    const timestamp = new Date().toTimeString().split(' ')[0];
    let logText = `[${timestamp}] ${message}`;
    if (data) {
      try {
        logText += ` ${typeof data === 'string' ? data : JSON.stringify(data)}`;
      } catch (e) {
        logText += ' [Complex Object]';
      }
    }
    setLogs(prev => [...prev, logText]);
  }, []);

  // 事件处理函数定义 - 必须在 useEffect 之前定义
  const handleReady = useCallback(() => {
    addLog('播放器准备就绪');
    setIsPlaying(true);
  }, [addLog]);

  const handlePlay = useCallback(() => {
    addLog('开始播放');
    setIsPlaying(true);
  }, [addLog]);

  const handlePause = useCallback(() => {
    addLog('暂停播放');
    setIsPlaying(false);
  }, [addLog]);

  const handleStop = useCallback(() => {
    // 停止并清理播放器实例
    if (wrPlayerInstance.current) {
      try {
        wrPlayerInstance.current.stop();
      } catch (e) {
        console.warn('停止播放器时出错:', e);
      }
      wrPlayerInstance.current = null;
    }
    
    setShowPlayer(false);
    setCurrentUrl('');
    setIsPlaying(false);
    setRetryCount(0); // 重置重试计数
    setIsMuted(true); // 重置静音状态
    addLog('停止播放');
  }, [addLog]);

  const handleToggleMute = useCallback(() => {
    if (videoRef.current) {
      const newMutedState = !isMuted;
      videoRef.current.muted = newMutedState;
      videoRef.current.volume = newMutedState ? 0 : 1;
      setIsMuted(newMutedState);
      addLog(newMutedState ? '已静音' : '已取消静音');
    }
  }, [isMuted, addLog]);

  const handleError = useCallback((err) => {
    addLog('播放器错误', err);
    setIsPlaying(false);
    
    // 如果是 WebRTC SDP 相关错误，可以尝试重连
    if (err && typeof err === 'object' && err.details) {
      const errorString = JSON.stringify(err.details);
      if (errorString.includes('setRemoteDescription') || errorString.includes('m-lines') || errorString.includes('demuxing')) {
        if (retryCount < 2) { // 最多重试2次
          addLog(`检测到 SDP 协商错误，将在 2 秒后重试 (${retryCount + 1}/2)`);
          setTimeout(() => {
            setRetryCount(prev => prev + 1);
            handleStop();
            setTimeout(() => {
              addLog(`重试连接，URL: ${currentUrl}`);
              setShowPlayer(true);
            }, 1000);
          }, 2000);
        } else {
          addLog('重试次数已达上限，请检查流媒体服务器配置');
          setRetryCount(0);
        }
      }
    }
  }, [addLog, retryCount, currentUrl, handleStop]);

  // 初始化和管理 WRPlayer 实例
  useEffect(() => {
    if (showPlayer && currentUrl && videoRef.current) {
      // 清理之前的实例
      if (wrPlayerInstance.current) {
        try {
          wrPlayerInstance.current.stop();
        } catch (e) {
          console.warn('清理播放器实例时出错:', e);
        }
        wrPlayerInstance.current = null;
      }

      // 创建新的 WRPlayer 实例
      try {
        const player = new WRPlayer({
          element: videoRef.current,
          url: currentUrl,
          type: 'webrtc',
          autoplay: true,
          debug: true,
          recvAudio: true,
          recvVideo: true,
          webrtcConfig: {
            simulcast: false,     // ⭐ 关键：禁用多路视频编码，避免 mid=2
            useCamera: false,     // web 项目的配置
            audioEnable: true,    // ⭐ 与 web 项目保持一致
            videoEnable: true,
            recvOnly: true,
            usedatachannel: false // web 项目的配置
          }
        });

        // 绑定事件
        player.on('ready', handleReady);
        player.on('play', handlePlay);
        player.on('pause', handlePause);
        player.on('error', handleError);

        wrPlayerInstance.current = player;
        playerRef.current = player;

        // 静音自动播放策略
        const startMutedAutoplay = async () => {
          try {
            // 1. 确保视频元素处于静音状态
            if (videoRef.current) {
              videoRef.current.muted = true;
              videoRef.current.volume = 0;
              addLog('设置视频为静音状态');
            }
            
            // 2. 调用 WRPlayer 的 play 方法
            await player.play();
            addLog('WRPlayer 开始播放');
            
            // 3. 直接调用 video 元素的 play 方法作为备用保障
            if (videoRef.current && videoRef.current.play) {
              try {
                await videoRef.current.play();
                addLog('视频元素静音自动播放成功');
                setNeedsUserInteraction(false); // 重置用户交互标志
              } catch (videoPlayError) {
                addLog('视频元素播放失败', videoPlayError.message);
                // 如果静音播放也失败，提示需要用户交互
                if (videoPlayError.name === 'NotAllowedError') {
                  setNeedsUserInteraction(true);
                  addLog('浏览器严格模式，需要用户点击才能播放');
                }
              }
            }
          } catch (error) {
            addLog('播放器播放失败', error.message);
            console.warn('静音自动播放失败:', error);
          }
        };

        // 延迟一点时间确保所有事件监听器都已绑定
        setTimeout(() => {
          startMutedAutoplay();
        }, 100);
        
      } catch (error) {
        addLog('创建播放器失败', error.message);
        handleError(error);
      }
    }

    // 清理函数
    return () => {
      if (wrPlayerInstance.current) {
        try {
          wrPlayerInstance.current.stop();
        } catch (e) {
          console.warn('清理播放器实例时出错:', e);
        }
        wrPlayerInstance.current = null;
      }
    };
  }, [showPlayer, currentUrl, handleReady, handlePlay, handlePause, handleError, handleStop, addLog]);

  const handleUrlChange = (e) => {
    setVideoUrl(e.target.value);
  };

  const handlePlayClick = () => {
    if (!videoUrl.trim()) {
      addLog('请输入视频/流 URL');
      return;
    }
    
    // 先停止当前播放器（如果有的话）
    if (showPlayer) {
      handleStop();
      // 延迟一下再启动新的播放器，确保资源完全释放
      setTimeout(() => {
        addLog(`启动播放器，URL: ${videoUrl}`);
        setCurrentUrl(videoUrl);
        setShowPlayer(true);
      }, 500);
    } else {
      addLog(`启动播放器，URL: ${videoUrl}`);
      setCurrentUrl(videoUrl);
      setShowPlayer(true);
    }
  };

  // PTZ API 初始化
  useEffect(() => {
    if (ptzApiUrl) {
      ptzApi.setConfig(ptzApiUrl, ptzToken, useProxy);
      addLog(`PTZ API配置: ${useProxy ? '使用代理模式' : '直连模式'} - ${ptzApiUrl}`);
    }
  }, [ptzApiUrl, ptzToken, useProxy, addLog]);

  // PTZ 控制命令处理
  const handlePtzCommand = useCallback(async (channelId, command, horizonSpeed, verticalSpeed, zoomSpeed) => {
    try {
      addLog(`PTZ控制: ${command}, 速度: H${horizonSpeed} V${verticalSpeed} Z${zoomSpeed}`);
      await ptzApi.ptz(deviceId, channelId, command, horizonSpeed, verticalSpeed, zoomSpeed);
    } catch (error) {
      addLog('PTZ控制失败', error.message);
    }
  }, [deviceId, addLog]);

  // 聚焦控制
  const handleFocusCommand = useCallback(async (channelId, command, speed) => {
    try {
      addLog(`聚焦控制: ${command}, 速度: ${speed}`);
      await ptzApi.focus(deviceId, channelId, command, speed);
    } catch (error) {
      addLog('聚焦控制失败', error.message);
    }
  }, [deviceId, addLog]);

  // 光圈控制
  const handleIrisCommand = useCallback(async (channelId, command, speed) => {
    try {
      addLog(`光圈控制: ${command}, 速度: ${speed}`);
      await ptzApi.iris(deviceId, channelId, command, speed);
    } catch (error) {
      addLog('光圈控制失败', error.message);
    }
  }, [deviceId, addLog]);

  // 预置点相关处理
  const handleQueryPresets = useCallback(async (channelId) => {
    try {
      addLog('查询预置点列表');
      const result = await ptzApi.queryPreset(deviceId, channelId);
      addLog('预置点查询成功', `共${Array.isArray(result) ? result.length : 0}个`);
      return result;
    } catch (error) {
      addLog('查询预置点失败', error.message);
      throw error;
    }
  }, [deviceId, addLog]);

  const handleAddPreset = useCallback(async (channelId, presetId) => {
    try {
      addLog(`添加预置点: ${presetId}`);
      await ptzApi.addPreset(deviceId, channelId, presetId);
      addLog('预置点添加成功');
    } catch (error) {
      addLog('添加预置点失败', error.message);
      throw error;
    }
  }, [deviceId, addLog]);

  const handleCallPreset = useCallback(async (channelId, presetId) => {
    try {
      addLog(`调用预置点: ${presetId}`);
      await ptzApi.callPreset(deviceId, channelId, presetId);
      addLog('预置点调用成功');
    } catch (error) {
      addLog('调用预置点失败', error.message);
      throw error;
    }
  }, [deviceId, addLog]);

  const handleDeletePreset = useCallback(async (channelId, presetId) => {
    try {
      addLog(`删除预置点: ${presetId}`);
      await ptzApi.deletePreset(deviceId, channelId, presetId);
      addLog('预置点删除成功');
    } catch (error) {
      addLog('删除预置点失败', error.message);
      throw error;
    }
  }, [deviceId, addLog]);

  return (
    <div className="max-w-4xl mx-auto p-5 font-sans">
      <div className="mb-8">
        <h2 className="text-xl font-semibold mb-4">智能视频播放器</h2>
        
        <div className="mb-6">
          {/* 视频播放器容器 - 只有在showPlayer为true时才显示 */}
          {showPlayer && (
            <div 
              className="relative border border-gray-300 mb-4"
              style={{ width: '100%', maxWidth: '800px', aspectRatio: '16 / 9' }}
            >
              <video
                ref={videoRef}
                controls={true}
                muted={isMuted}
                autoPlay={true}
                playsInline={true}
                className="w-full h-full"
                style={{ display: 'block', width: '100%', height: '100%', objectFit: 'contain' }}
              />
            </div>
          )}
          
          {/* 控制面板 */}
          <div className="mt-3">
            <input
              type="text"
              value={videoUrl}
              onChange={handleUrlChange}
              placeholder="输入任何格式的视频/流 URL，将自动检测类型"
              className="w-3/5 p-2 border border-gray-300 rounded mr-2"
            />

            <button
              onClick={handlePlayClick}
              disabled={isPlaying}
              className={`px-4 py-2 text-white rounded mr-2 ${
                isPlaying 
                  ? 'bg-gray-400 cursor-not-allowed' 
                  : 'bg-blue-500 hover:bg-blue-600'
              }`}
            >
              播放
            </button>
            <button
              onClick={handleStop}
              disabled={!showPlayer}
              className={`px-4 py-2 text-white rounded mr-2 ${
                !showPlayer 
                  ? 'bg-gray-400 cursor-not-allowed' 
                  : 'bg-red-500 hover:bg-red-600'
              }`}
            >
              停止
            </button>
            
            {/* 静音切换按钮 */}
            {showPlayer && (
              <button
                onClick={handleToggleMute}
                className={`px-4 py-2 text-white rounded mr-2 ${
                  isMuted 
                    ? 'bg-yellow-500 hover:bg-yellow-600' 
                    : 'bg-green-500 hover:bg-green-600'
                }`}
              >
                {isMuted ? '🔇 取消静音' : '🔊 静音'}
              </button>
            )}
            
            {/* PTZ控制切换按钮 */}
            <button
              onClick={() => setShowPtzControls(!showPtzControls)}
              className={`px-4 py-2 text-white rounded ${
                showPtzControls 
                  ? 'bg-purple-600 hover:bg-purple-700' 
                  : 'bg-purple-500 hover:bg-purple-600'
              }`}
            >
              {showPtzControls ? '🎮 隐藏云台控制' : '🎮 显示云台控制'}
            </button>
          </div>
          
          {/* PTZ配置面板 */}
          {showPtzControls && (
            <div className="mt-4 p-4 border border-gray-300 rounded bg-gray-50">
              <h3 className="text-lg font-semibold mb-3">PTZ云台控制配置</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div>
                  <label className="block text-sm font-medium mb-1">SIP服务地址:</label>
                  <input
                    type="text"
                    value={ptzApiUrl}
                    onChange={(e) => setPtzApiUrl(e.target.value)}
                    placeholder="http://ip:port"
                    className="w-full p-2 border border-gray-300 rounded text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">API Key:</label>
                  <input
                    type="text"
                    value={ptzToken}
                    onChange={(e) => setPtzToken(e.target.value)}
                    placeholder="API Key"
                    className="w-full p-2 border border-gray-300 rounded text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">设备ID:</label>
                  <input
                    type="text"
                    value={deviceId}
                    onChange={(e) => setDeviceId(e.target.value)}
                    placeholder="设备ID"
                    className="w-full p-2 border border-gray-300 rounded text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">通道ID:</label>
                  <input
                    type="text"
                    value={channelId}
                    onChange={(e) => setChannelId(e.target.value)}
                    placeholder="通道ID"
                    className="w-full p-2 border border-gray-300 rounded text-sm"
                  />
                </div>
              </div>
              

              {/* PTZ控制组件 */}
              <div className="flex flex-wrap gap-4">
                <PtzControls
                  channelId={channelId}
                  onPtzCommand={handlePtzCommand}
                  onFocusCommand={handleFocusCommand}
                  onIrisCommand={handleIrisCommand}
                  disabled={!ptzApiUrl || !deviceId || !channelId || !ptzToken}
                />
                <PtzPresets
                  channelId={channelId}
                  onQueryPresets={handleQueryPresets}
                  onAddPreset={handleAddPreset}
                  onCallPreset={handleCallPreset}
                  onDeletePreset={handleDeletePreset}
                  disabled={!ptzApiUrl || !deviceId || !channelId || !ptzToken}
                />
                <PtzAdvanced
                  channelId={channelId}
                  deviceId={deviceId}
                  ptzApi={ptzApi}
                  onLog={addLog}
                  disabled={!ptzApiUrl || !deviceId || !channelId || !ptzToken}
                />
              </div>
            </div>
          )}

          {/* 日志显示 */}
          <div 
            className="mt-4 h-40 overflow-y-auto border border-gray-300 p-3 font-mono text-sm bg-gray-50"
          >
            {logs.map((log, index) => (
              <div key={index} className="mb-1">
                {log}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* 状态指示器 */}
      {isPlaying && (
        <div className="mt-4 p-3 bg-green-100 border border-green-400 text-green-700 rounded">
          <p className="font-medium">✓ 播放器状态：{isPlaying ? '播放中' : '已停止'}</p>
          <p className="text-sm mt-1">🔊 音频状态：{isMuted ? '静音模式（点击取消静音按钮开启声音）' : '声音已开启'}</p>
        </div>
      )}
      
      {/* 用户交互提示 */}
      {needsUserInteraction && (
        <div className="mt-4 p-3 bg-yellow-100 border border-yellow-400 text-yellow-700 rounded">
          <p className="font-medium">⚠️ 需要用户交互</p>
          <p className="text-sm mt-1">浏览器阻止了自动播放，请点击播放按钮手动开始播放</p>
        </div>
      )}
    </div>
  );
} 